<template>
  <div class="schoolList" v-for="(data, index) in schoolListArr" :key="index">
    <div class="flex">
      <div class="schoolList-Left">
        <h1 class="add" v-if="data.isNewly">新增</h1>
        <div v-else>
          <div class="df" style="align-items: baseline">
            <div style="font-size: 35px; font-weight: bold">
              {{ data.chance }}
            </div>
            <span>%</span>
          </div>

          <div class="schoolList-Left-size">{{ data.probabilityExplain }}</div>
        </div>
        <div
          :class="
            data.chance_lv == 1
              ? 'chance1'
              : data.chance_lv == 2
                ? 'chance2'
                : 'chance3'
          "
          class="schoolList-Left-number"
        >
          {{ data.chance_lv == 1 ? '冲' : data.chance_lv == 2 ? '稳' : '保' }}
        </div>
      </div>
      <div
        class="schoolList-Center"
        style="flex: 1 1 0%"
        @click="toSchoolDetail(data)"
      >
        <div class="schoolName" v-html="highlightText(data.collegeName)"></div>
        <div class="schoolList-size">
          <p>
            代码: {{ data.collegeEnrollCode }} |
            {{ data.features.join(' / ') }} |
            {{
              data.provinceName +
              ' ' +
              data.cityName +
              ' / ' +
              data.categories.join(' / ') +
              ' / ' +
              data.natureType +
              ' / ' +
              '排名' +
              (data.rank <= 0 ? '-' : data.rank)
            }}
          </p>
        </div>
      </div>
      <div class="schoolList-people" style="width: 128px">
        <div class="schoolList-Number" style="font-size: 35px">
          {{ data.planNum }}<span style="font-size: 12px">人</span>
        </div>
        <div class="schoolList-title">物理+不限</div>
        <div class="schoolList-title" v-if="!data.majorsInfo">
          {{
            (data.learnYear ? data.learnYear : '-') +
            '年 ￥' +
            (data.cost ? data.cost : '-')
          }}
        </div>
      </div>
      <div class="schoolList-grade">
        <div class="schoolList-grade-left" style="width: 25%">
          <div class="schoolList-grade-size">录取人数</div>
          <div class="schoolList-grade-size">线差</div>
          <div class="schoolList-grade-size">最低分</div>
          <div class="schoolList-grade-size">最低位次</div>
          <div class="schoolList-grade-size schoolList-grade-size-icon">
            <span>等效位差</span>
            <el-tooltip placement="top">
              <template #content>
                什么是等效位差？
                <br />
                历年等效位差根据考生历年的等效位-历年位次的差值得出，
                <br />
                换算后的等效位差可更精准的与历年位次进行比较。
              </template>
              <QuestionFilled style="width: 12px; margin-left: 8px" />
            </el-tooltip>
          </div>
        </div>

        <div
          v-for="moreItem in data.moreYear"
          :key="moreItem.minScore"
          style="width: 25%"
        >
          <div v-if="moreItem.hasPlan" class="schoolList-grade-left">
            <div class="schoolList-grade-size-number">
              {{ moreItem.enterNum == 0 ? '-' : moreItem.enterNum }}
            </div>
            <div class="schoolList-grade-size-number">
              {{ moreItem.lineDiff || '-' }}
            </div>
            <div class="schoolList-grade-size-number alitem">
              {{ moreItem.minScore == 0 ? '-' : moreItem.minScore }}
              <div
                v-if="
                  (moreItem.zjText * 1 > 0 && moreItem.minScore * 1 > 0) ||
                  moreItem.zjText == '有征集'
                "
                style="background-color: #fbc7c2; color: red"
              >
                征
              </div>
            </div>
            <div class="schoolList-grade-size-number">
              {{ moreItem.minRank == 0 ? '-' : moreItem.minRank }}
            </div>
            <div class="schoolList-grade-size-number alitem">
              <template
                v-for="(item, index) in getFormatEquivalentBitDifference(
                  moreItem.equivalentBitDifference,
                )"
                :key="index"
              >
                <span :style="{ color: item.color }">
                  {{ item.text }}
                </span>
              </template>
            </div>
          </div>
          <div v-else class="schoolList-grade-left">
            <span
              class="schoolList-grade-size-number alitem"
              style="height: 100%"
              >未招生</span
            >
          </div>
        </div>
      </div>
      <div
        style="width: 12%; cursor: pointer; flex-direction: column"
        class="cloum alitem center"
      >
        <!-- <el-dropdown @command="handleCommand"> -->
        <el-dropdown :disabled="data.isFit == 0 ? true : false">
          <span class="el-dropdown-link">
            <el-button
              :style="{
                color: data.isFit == 0 ? '#ccc !important' : '',
                border: data.isFit == 0 ? '1px solid #ccc !important' : '',
              }"
              type="primary"
              style="width: 93px"
              :class="
                getFilledCollegeKey(data).length > 0
                  ? 'zyb-fill'
                  : 'zyb-notfill'
              "
              >填报为{{ getFilledCollegeKey(data) }}
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <div
              style="
                text-align: center;
                margin-top: 10px;
                color: red;
                font-size: 12px;
              "
              v-if="data.isFit == 0"
            >
              选科不符
            </div>
          </span>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="key in volunteerKeys"
                :key="key"
                @click="
                  onClickVolunteerItem(getFilledCollegeKey(data), key, data)
                "
                :style="getFilledKey(key) ? 'color: #165dff' : ''"
                command="a"
              >
                {{ key }}志愿
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div
          class="schoolList-tzy-button alitem margintop"
          @click="onClickShowMajors(data)"
        >
          专业
          {{ data.majorsInfo ? data.majorsInfo.length : 0 }}
          <el-icon size="20">
            <ArrowDown v-if="!isShowMajors(data)" />
            <ArrowUp v-else />
          </el-icon>
        </div>
      </div>
    </div>
    <div
      style="width: 100%; background-color: #fafbfe; display: flex"
      v-for="major in data.majorsInfo"
      :key="major.professionRealName"
    >
      <div
        v-if="isShowMajors(data)"
        style="display: flex; width: 100%; border-bottom: 1px solid #e5e6eb"
      >
        <div class="schoolList-Left">
          <div style="display: flex; align-items: baseline">
            <div style="font-size: 35px; font-weight: bold">
              {{ major.chance }}
            </div>
            %
          </div>
          <div class="schoolList-Left-size">{{ major.probabilityExplain }}</div>
        </div>
        <div
          class="schoolList-Center"
          style="flex: 1 1 0%"
          @click="handleMajorDet(major)"
        >
          <div
            class="schoolName-size"
            v-html="highlightText(major.professionRealName)"
          ></div>
          <div style="font-size: 12px; margin-left: 20px">
            {{ major.remarkExt }}
          </div>
          <div class="schoolList-size">
            <div>
              代码:
              {{
                major.professionEnrollCode ? major.professionEnrollCode : '-'
              }}
              <span v-if="!!major.mseLevel"> | </span>
              <span v-if="!!major.mseLevel" class="mseLevel">{{
                major.mseLevel
              }}</span>
            </div>
          </div>
        </div>
        <div class="schoolList-people" style="width: 128px">
          <div class="schoolList-Number" style="font-size: 35px">
            {{ major.planNum ? major.planNum : '-' }}
            <span style="font-size: 12px">人</span>
          </div>
          <div class="schoolList-title">物理+不限</div>
          <div class="schoolList-title">
            {{
              (major.learnYear ? major.learnYear : '-') +
              '年 ￥' +
              (major.cost ? major.cost : '-')
            }}
          </div>
        </div>
        <div class="schoolList-grade">
          <div class="schoolList-grade-left" style="width: 25%">
            <div class="schoolList-grade-size">录取人数</div>
            <div class="schoolList-grade-size">线差</div>
            <div class="schoolList-grade-size">最低分</div>
            <div class="schoolList-grade-size">最低位次</div>
            <div class="schoolList-grade-size schoolList-grade-size-icon">
              <span>等效位差</span>
              <el-tooltip placement="top">
                <template #content>
                  什么是等效位差？
                  <br />
                  历年等效位差根据考生历年的等效位-历年位次的差值得出，
                  <br />
                  换算后的等效位差可更精准的与历年位次进行比较。
                </template>
                <QuestionFilled style="width: 12px; margin-left: 8px" />
              </el-tooltip>
            </div>
          </div>
          <div
            v-for="moreItem in major.moreYear"
            style="width: 25%"
            :key="moreItem.enterNum"
          >
            <div class="schoolList-grade-left">
              <div class="schoolList-grade-size-number">
                {{ moreItem.enterNum == 0 ? '-' : moreItem.enterNum }}
              </div>
              <div class="schoolList-grade-size-number">
                {{ moreItem.lineDiff || '-' }}
              </div>
              <div class="schoolList-grade-size-number alitem">
                {{ moreItem.minScore == 0 ? '-' : moreItem.minScore }}
                <div
                  v-if="
                    (moreItem.zjText * 1 > 0 && moreItem.minScore * 1 > 0) ||
                    moreItem.zjText == '有征集'
                  "
                  style="background-color: #fbc7c2; color: red"
                >
                  征
                </div>
              </div>
              <div class="schoolList-grade-size-number">
                {{ moreItem.minRank == 0 ? '-' : moreItem.minRank }}
              </div>
              <div class="schoolList-grade-size-number alitem">
                <template
                  v-for="(item, index) in getFormatEquivalentBitDifference(
                    moreItem.equivalentBitDifference,
                  )"
                  :key="index"
                >
                  <span :style="{ color: item.color }">
                    {{ item.text }}
                  </span>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div style="width: 12%; cursor: pointer" class="alitem center">
          <div
            :style="{
              color: data.isFit == 0 ? '#ccc !important' : '',
              border: data.isFit == 0 ? '1px solid #ccc !important' : '',
            }"
            class="schoolList-look-button"
            style="width: 60px"
            :class="getFilledMajorIndex(data, major) > 0 ? 'select' : ''"
            @click="onClickTianbao(data, major)"
          >
            {{
              getFilledMajorIndex(data, major) > 0
                ? '已填' + getFilledMajorIndex(data, major)
                : '填报'
            }}
          </div>
          <span
            v-if="data.majorEnrollTypesLable"
            style="font-size: 14px; color: #ff7d00"
            >{{ major.majorEnrollTypesLable }}</span
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { watch, ref, computed, watchEffect } from 'vue';
// import volunteersStore from '@/store/modules/volunteerInfos'
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { safeFormatEquivalentBitDifference } from '@/utils/formatEquivalentBitDifference.js';

const router = useRouter();

// const volunteerStore = volunteersStore()
const store = useStore();

const props = defineProps({
  // 院校列表数据
  schoolListArr: {
    type: Array,
    default: () => [],
  },
  // 可填写志愿表数量
  volunteerNumber: {
    type: String,
    default: '0',
  },
  // 筛选条件
  userSearchDate: {
    type: Array,
    default: () => [],
  },
});
const userSearchDateString = ref('');
watchEffect(() => {
  userSearchDateString.value = props.userSearchDate.map((item) => item.name);
});
const highlightText = (text) => {
  if (userSearchDateString.value.length === 0) return text; // 没有选中标签时直接返回原文本
  // 遍历选中的标签，构建正则表达式
  const regex = new RegExp(`(${userSearchDateString.value.join('|')})`, 'gi'); // 使用 | 作为正则的 OR 操作符
  // 使用 \\\$1 来正确引用正则的捕获组
  return text.replace(
    regex,
    '<span style="color: #409eff; font-weight: bold;">$&</span>', // 直接使用 $& 引用匹配到的整个字符串
  );
};
watch(
  () => props.volunteerNumber,
  () => {
    getVolunteerDataNumber();
  },
);

// 动态获取等效位差的页面结构
const getFormatEquivalentBitDifference = (val) => {
  return safeFormatEquivalentBitDifference(val);
};

// 点击院校跳转
function toSchoolDetail(data) {
  localStorage.setItem('collegeDetAct', '1');
  localStorage.setItem('code', data.collegeCode);
  window.open(
    router.resolve('/college/detail?collegecode=' + data.collegeCode).href,
    '_blank',
  );
}

// 点击专业跳转
function handleMajorDet(item) {
  let level = '';
  if (item.eduLevel == '本科') {
    level = 'benke';
  } else if (item.eduLevel == '专科') {
    level = 'zhuanke';
  }
  localStorage.setItem('level', level);
  const url =
    '/majorLibrary/majorLibraryDet' +
    '?code=' +
    item.majorCode +
    '&name=' +
    item.professionRealName +
    '&level=' +
    level;
  window.open(url, '_blank');
}

// 可填报志愿表key：[A-Z]
const volunteerKeys = ref([]);
// 当前填报志愿表数据：{"A":{}, "B":{}, ... , "Z":{}}
const volunteerInfos = ref(
  computed(() =>
    store.getters.tianbao.volunteerInfos.length
      ? store.getters.tianbao.volunteerInfos
      : [],
  ),
);
// 展开查看专业列表的学校ID数组
const showMajorsSchoolIDs = ref([]);
/*
 * 根据四川高考类型可填报志愿表数量获取相同数量的志愿表key：A-Z，例如四川志愿表数量为9，volunteerKeys等于A-I
 * props.volunteerNumber 可填报志愿表数量
 */
function getVolunteerDataNumber() {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numKeys = Math.ceil(props.volunteerNumber / 26);

  for (let i = 0; i < props.volunteerNumber; i++) {
    let letterIndex = i % 26;
    let key =
      alphabet[letterIndex] + (numKeys === 1 ? '' : Math.floor(i / 26 + 1));
    volunteerKeys.value.push(key);
  }
}

// 点击展开收起专业列表
function onClickShowMajors(data) {
  const index = showMajorsSchoolIDs.value.indexOf(data.id);
  if (index >= 0) {
    showMajorsSchoolIDs.value.splice(index, 1);
  } else {
    showMajorsSchoolIDs.value.push(data.id);
  }
}

// 是否展开专业列表
function isShowMajors(data) {
  return showMajorsSchoolIDs.value.includes(data.id);
}

// 是否已填志愿表并返回填报的志愿表Key
function getFilledCollegeKey(data) {
  let foundItem = volunteerInfos.value.find((item) => item.id === data.id);
  return foundItem ? foundItem.vkey : '';
}

// 是否已填志愿表
function getFilledKey(key) {
  return volunteerInfos.value.some((data) => data.vkey.includes(key));
}

/*
 * 点击志愿表选项
 * oldKey: 原有的志愿表key
 * key: 即将切换的志愿表key
 * data: 填报的学校数据
 */
function onClickVolunteerItem(oldKey, key, data) {
  if (data.isFit != 1 || (oldKey && key && oldKey.includes(key))) return;

  const allKey = volunteerInfos.value.map((item) => item.vkey);
  const toVolunteer =
    volunteerInfos.value.filter((item) => item.vkey == key)[0] || {};
  const oldVolunteer =
    volunteerInfos.value.filter((item) => item.vkey == oldKey)[0] || {};
  let volunteer = oldVolunteer;

  if (toVolunteer.vkey || oldVolunteer.vkey) {
    if (oldKey) {
      let index = volunteerInfos.value.findIndex((item) => item.vkey == oldKey);
      volunteerInfos.value.splice(index, 1);

      const keyArr = volunteerInfos.value
        .map((item) => item.vkey)
        .filter((item) => item.includes(oldKey.charAt(0)));

      keyArr.forEach((item, index) => {
        let volunteer = volunteerInfos.value.find((i) => i.vkey == item) || {};
        volunteer.vkey =
          index > 0 ? oldKey.charAt(0) + index : oldKey.charAt(0);

        volunteerInfos.value.splice(
          volunteerInfos.value.indexOf(volunteer),
          1,
          volunteer,
        );
      });
    }

    const keyArr = allKey.filter((item) => item.includes(key));
    volunteer = JSON.parse(JSON.stringify(data));
    volunteer.majorsInfo =
      oldVolunteer.majorsInfo?.length > 0 ? oldVolunteer.majorsInfo : [];

    if (toVolunteer.vkey) {
      key = key + keyArr.length;
    }
  } else {
    volunteer = JSON.parse(JSON.stringify(data));
    volunteer.majorsInfo = [];
  }

  // 添加展开专业列表的学校ID
  showMajorsSchoolIDs.value.push(data.id);
  // 设置新的志愿表
  volunteer.vkey = key;
  volunteerInfos.value.push(volunteer);

  // 排序
  volunteerInfos.value = volunteerInfos.value.sort((a, b) => {
    const scoreA = a.vkey.charCodeAt(0);
    const scoreB = b.vkey.charCodeAt(0);

    // 按照 ASCII 码升序排序
    return scoreA - scoreB;
  });

  console.log('volunteerInfos', volunteerInfos.value);

  store.dispatch('tianbao/setVolunteerInfos', [...volunteerInfos.value]);
}

// 点击填报按钮 data:学校数据  major:专业数据
function onClickTianbao(data, major) {
  if (data.isFit == 1) {
    let volunteer = volunteerInfos.value.find((item) => item.id === data.id);

    if (volunteer) {
      // 已填报学校，判断填报or取消填报专业
      let majorsInfo = volunteer.majorsInfo || [];
      let mIndex = majorsInfo.findIndex((item) => item.id === major.id);

      if (mIndex >= 0) {
        majorsInfo.splice(mIndex, 1);
      } else {
        majorsInfo.push(major);
      }

      // 更新志愿表数据
      volunteer.majorsInfo = majorsInfo;
      volunteerInfos.value.splice(
        volunteerInfos.value.indexOf(volunteer),
        1,
        volunteer,
      );
    } else {
      // 未填报学校，提示请选择学校
      ElMessage({
        message: '请先选择学校',
        type: 'warning',
      });
    }

    // store.dispatch("tianbao/setVolunteerInfos", volunteerInfos.value);
  }
}

// 判断是否填报专业并返回当前填报专业数量
function getFilledMajorIndex(data, major) {
  let volunteer = volunteerInfos.value.find((item) => item.id === data.id);

  let index = volunteer?.majorsInfo?.findIndex((item) => item.id == major.id);

  return index + 1;
}

function removeVolunteerInfos() {
  volunteerInfos.value = [];
}

defineExpose({
  removeVolunteerInfos,
});
</script>
<style lang="scss" scoped>
:deep(.el-tooltip__trigger:focus-visible) {
  outline: unset;
}

.schoolList {
  display: flex;
  flex-direction: column;
  border-right: none;
  background: #fff;
  position: relative;
  border-bottom: 1px solid #e5e6eb;

  .schoolList-tzy-button {
    color: #165dff;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    font-size: 12px;
  }

  .schoolList-look-button {
    color: #165dff;
    width: 90px;
    height: 40px;
    background-color: #fff;
    border: 1px solid #165dff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
  }

  .schoolList-look-button.select {
    color: white;
    background-color: #165dff;
  }

  .schoolList-grade {
    display: flex;
    width: 40%;

    .schoolList-grade-left {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 100%;

      .schoolList-grade-size {
        height: 25%;
        padding: 10px 5px;
        text-align: left;
        font-size: 12px;
        font-weight: 400;
        line-height: 12px;
        border-bottom: 1px solid #f2f3f5;
        border-right: 1px solid #f2f3f5;
      }

      .schoolList-grade-size-number {
        height: 25%;
        padding: 10px 5px;
        text-align: left;
        font-size: 12px;
        font-weight: 400;
        line-height: 12px;
        border-bottom: 1px solid #f2f3f5;
        border-right: 1px solid #f2f3f5;
        padding-left: 10px;
      }

      .schoolList-grade-size-icon {
        align-items: center;
        display: flex;
        flex-direction: row;
      }
    }
  }

  .schoolList-people {
    display: flex;
    flex-direction: column;
    text-align: center;
    padding: 18px 0;
    border-right: 1px solid #e5e6eb;

    .schoolList-Number {
      text-align: center;
      font-size: 20px;
      font-weight: 400;
      color: #1d2129;
      line-height: 24px;
    }

    .schoolList-title {
      font-size: 12px;
      font-weight: 400;
      color: #86909c;
      line-height: 1.5;
    }
  }

  .schoolList-Center {
    cursor: pointer;
    min-width: 100px;
    margin-bottom: 10px;

    .schoolName {
      font-size: 18px;
      font-weight: 500;
      color: #1d2129;
      line-height: 27px;
      margin-left: 20px;
      margin-top: 20px;
    }

    .schoolName-size {
      font-size: 14px;
      font-weight: 400;
      color: #1d212c;
      line-height: 27px;
      margin-left: 20px;
      margin-top: 20px;
    }

    .schoolList-size {
      font-size: 12px;
      font-weight: 400;
      color: #86909c;
      line-height: 24px;
      display: flex;
      margin-left: 20px;
      align-items: center;

      .mseLevel {
        background-color: #fbe6e8;
        padding: 2px 4px;
        font-size: 10px;
        color: #f54f4a;
      }
    }

    .schoolList-bottom {
      display: flex;
      margin-left: 20px;
      margin-top: 10px;
      margin-bottom: 10px;

      .schoolList-bottom-size {
        background: #fff;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #bcc3cc;
        font-size: 12px;
        font-weight: 400;
        color: #86909c;
        padding: 0 4px;
        margin: 0 4px;
      }
    }
  }

  .schoolList-Left {
    width: 7%;
    padding-left: 20px;
    padding-top: 18px;
    padding-bottom: 18px;
    border-right: 1px solid #f2f3f5;

    .schoolList-Left-size {
      text-align: left;
      font-size: 12px;
      font-family:
        PingFang SC-Regular,
        PingFang SC;
      font-weight: 400;
      color: #86909c;
      line-height: 12px;
    }

    .schoolList-Left-number {
      width: 20px;
      height: 20px;
      // background-color: #F53F3F;
      text-align: center;
      line-height: 20px;
      border-radius: 4px;
      color: #fff;
    }
  }

  .zyb-fill {
    background-color: #165dff;
    color: white;
  }

  .zyb-notfill {
    background-color: transparent;
    color: #165dff;
    border: #165dff 2rpx solid;
  }
}

.chance1 {
  background-color: #f53f3f;
  margin-top: 10px;
}

.chance2 {
  background-color: #ff8c33;
}

.chance3 {
  background-color: #00bf10;
}
.add {
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: inherit;
  font-size: 24px;
}
</style>
